package com.opesoft.pf.jpa;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

public abstract class SimpleBO<T>
{
	private Class<T> _T;

	Logger log=Logger.getLogger(this.getClass());

	@SuppressWarnings("unchecked")
	public SimpleBO()
	{
		_T=(Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		log.debug("Create new SimpleBO<"+_T+">");
	}

	@SuppressWarnings({"unchecked","hiding"})
	public <T> T find(String id) throws Exception
	{
		EntityManager em=SessionManager.open();
		T t=(T)em.find(_T,Long.valueOf(id));
		SessionManager.rollback();
		return t;
	}

	public void insert(T t) throws Exception
	{
		EntityManager em=SessionManager.open();
		em.persist(t);
		SessionManager.commit();
	}

	public void del(String[] ids) throws Exception
	{
		if(ids!=null)
		{
			EntityManager em=SessionManager.open();
			for(int i=0;i<ids.length;i++)
			{
				em.remove(em.find(_T,Long.valueOf(ids[i])));
			}
			SessionManager.commit();
		}
	}

	public void update(T t) throws Exception
	{
		EntityManager em=SessionManager.open();
		t=em.merge(t);
		em.merge(t);
		SessionManager.commit();
	}
}
